<template>
  <main class="bg-light-400 w-full h-[100vh] pb-[12px] pb-[20px]">
    <template v-if="!loading && topic">
      <exam-header
        :title="topic.test_name"
        :time_limit="topic.time_limit"
        @calculate-elapsed-time="calculateElapsedTime"
        @exam-time-end="examTimeEnd"
      />
      <var-swipe
        class="swipe-example"
        :loop="false"
        :indicator="false"
        :touchable="false"
        ref="swipe"
      >
        <var-swipe-item v-for="(i, index) in topic.singles" :key="i.key">
          <div class="w-full">
            <div class="mb-[10px] px-[14px] bg-white pt-[17px] pb-[26.5px]">
              <h2
                class="text-[12px] px-[6px] rounded-full border-[2px] py-[4px] border-solid border-[#fdba5f] w-[52px]"
              >
                单选题
              </h2>
              <header class="text-[16px] mt-[23px] text-[#4A4A4A]">
                {{ index + 1 }}.
                {{ i.single_name }}
              </header>
            </div>
            <div class="bg-white px-[14px] py-[1.6vw] pb-[4vw]">
              <var-radio-group
                direction="vertical"
                v-model="singlesAnswer[index].single_key"
                :key="i.key"
                @change="handleRadioChange(i.key, index)"
              >
                <var-radio checked-value="A" icon-size="4vw" class="mt-[20px]">
                  <span class="text-[13px]">A.{{ i.A }}</span>
                </var-radio>
                <var-radio checked-value="B" icon-size="4vw" class="mt-[20px]">
                  <span class="text-[13px]">B.{{ i.B }}</span>
                </var-radio>
                <var-radio checked-value="C" icon-size="4vw" class="mt-[20px]">
                  <span class="text-[13px]">C.{{ i.C }}</span>
                </var-radio>
                <var-radio checked-value="D" icon-size="4vw" class="mt-[20px]">
                  <span class="text-[13px]">D.{{ i.D }}</span>
                </var-radio>
              </var-radio-group>
            </div>
          </div>
        </var-swipe-item>
        <var-swipe-item v-for="(i, index) in topic.selections" :key="i.key">
          <div class="w-full">
            <div class="mb-[10px] px-[14px] bg-white pt-[17px] pb-[26.5px]">
              <h2
                class="text-[12px] px-[6px] rounded-full border-[2px] py-[4px] border-solid border-[#fdba5f] w-[52px]"
              >
                多选题
              </h2>
              <header class="text-[16px] mt-[23px] text-[#4A4A4A]">
                {{ index + 1 }}.
                {{ i.selection_name }}
              </header>
            </div>
            <div class="bg-white px-[14px] py-[1.6vw] pb-[4vw]">
              <var-checkbox-group
                direction="vertical"
                v-model="selectionsAnswer[index].selection_key"
                :key="i.key"
                @change="handleSelectChange(i.key, index)"
              >
                <var-checkbox checked-value="A" icon-size="4vw" class="mt-[20px]">
                  <span class="text-[13px]">A.{{ i.A }}</span>
                </var-checkbox>
                <var-checkbox checked-value="B" icon-size="4vw" class="mt-[20px]">
                  <span class="text-[13px]">B.{{ i.B }}</span>
                </var-checkbox>
                <var-checkbox checked-value="C" icon-size="4vw" class="mt-[20px]">
                  <span class="text-[13px]">C.{{ i.C }}</span>
                </var-checkbox>
                <var-checkbox checked-value="D" icon-size="4vw" class="mt-[20px]">
                  <span class="text-[13px]">D.{{ i.D }}</span>
                </var-checkbox>
              </var-checkbox-group>
            </div>
          </div>
        </var-swipe-item>
        <var-swipe-item v-for="(i, index) in topic.judges" :key="i.key">
          <div class="w-full">
            <div class="mb-[10px] px-[14px] bg-white pt-[17px] pb-[26.5px]">
              <h2
                class="text-[12px] px-[6px] rounded-full border-[2px] py-[4px] border-solid border-[#fdba5f] w-[52px]"
              >
                判断题
              </h2>
              <header class="text-[16px] mt-[23px] text-[#4A4A4A]">
                {{ index + 1 }}.
                {{ i.judge_name }}
              </header>
            </div>
            <div class="bg-white px-[14px] py-[1.6vw] pb-[4vw]">
              <var-radio-group
                direction="vertical"
                v-model="judgesAnswer[index].judge_key"
                :key="i.key"
                @change="handleJudgeChange(i.key, index)"
              >
                <var-radio :checked-value="0" icon-size="4vw" class="mt-[20px]">
                  <span class="text-[13px]">错</span>
                </var-radio>
                <var-radio :checked-value="1" icon-size="4vw" class="mt-[20px]">
                  <span class="text-[13px]">对</span>
                </var-radio>
              </var-radio-group>
            </div>
          </div>
        </var-swipe-item>
      </var-swipe>
      <div class="justify-center flex mt-[20px]" v-if="isAllDo">
        <var-button type="info" class="!rounded-full w-[200px]" @click="submitExam">
          交卷
        </var-button>
      </div>
      <ul
        class="fixed bottom-0 left-0 bg-white w-full py-[9px] flex justify-between items-center px-[34px]"
      >
        <li class="flex-col justify-center items-center" @click="swipe.prev">
          <div class="flex justify-center">
            <img :src="on" class="w-[20px]" />
          </div>
          <p class="text-[11px] mt-[4px]">上一题</p>
        </li>
        <li class="flex-col justify-center" @click="popup = true">
          <div class="flex justify-center">
            <var-icon name="notebook" size="5.3vw" color="#909090" />
          </div>
          <p class="text-[11px] mt-[4px]">答题卡</p>
        </li>
        <li class="flex-col justify-center items-center" @click="swipe.next">
          <div class="flex justify-center">
            <img :src="down" class="w-[20px]" />
          </div>
          <p class="text-[11px] mt-[4px]">下一题</p>
        </li>
      </ul>
    </template>
    <template v-else>
      <var-skeleton v-for="i in 2" title :key="i" :loading="loading" :rows="4" class="enter-y" />
    </template>
    <var-popup position="bottom" v-model:show="popup">
      <main class="py-[20px]">
        <h2 class="text-[20px] font-bold text-[#585757] px-[10px] pb-[10px]">答题卡</h2>
        <var-divider />
        <section class="mt-[16px]">
          <h3 class="px-[10px]">单选题</h3>
          <ul class="grid grid-cols-6 mt-[10px]">
            <li
              v-for="i in topic?.singles.length"
              :key="i"
              class="flex justify-center"
              @click="swipe.to(i - 1)"
            >
              <div
                class="h-[8vw]"
                :class="singlesAnswer[Number(i) - 1].single_id !== 0 ? 'active' : ''"
              >
                {{ i }}
              </div>
            </li>
          </ul>
        </section>
        <section class="mt-[16px]">
          <h3 class="px-[10px]">多选题</h3>
          <ul class="grid grid-cols-6 mt-[10px]">
            <li
              v-for="i in topic?.selections.length"
              :key="i"
              class="flex justify-center"
              @click="swipe.to(i - 1 + topic!.singles.length)"
            >
              <div
                class="h-[8vw]"
                :class="selectionsAnswer[Number(i) - 1].selection_id !== 0 ? 'active' : ''"
              >
                {{ i }}
              </div>
            </li>
          </ul>
        </section>
        <section class="mt-[16px]">
          <h3 class="px-[10px]">判断题</h3>
          <ul class="grid grid-cols-6 mt-[10px]">
            <li
              v-for="i in topic?.judges.length"
              :key="i"
              class="flex justify-center"
              @click="swipe.to(i - 1 + topic!.singles.length + topic!.selections.length)"
            >
              <div
                class="h-[8vw]"
                :class="judgesAnswer[Number(i) - 1].judge_id !== 0 ? 'active' : ''"
              >
                {{ i }}
              </div>
            </li>
          </ul>
        </section>
      </main>
    </var-popup>
  </main>
</template>

<script setup lang="ts">
  import { getStudentAppExamQuestions } from '@/api/user';
  import { ExamTopic } from '@/utils/interface';
  import ExamHeader from './components/ExamHeader.vue';
  import on from '@/assets/icon/starexam_on.png';
  import down from '@/assets/icon/starexam_down.png';
  import { Snackbar } from '@varlet/ui';
  import { studentAppSubmitExam } from '@/api/user';
  import { useUserInfoStoreWithOut } from '@/stores/modules/userInfo';

  let popup = ref(false);
  let swipe = ref<any>(null);
  const route = useRoute();
  const router = useRouter();
  const test_id = route.params.id;

  let loading = ref(true);
  if (!test_id) {
    router.back();
  }
  let topic = ref<ExamTopic>();

  let singlesAnswer = ref<{ single_key: string; single_id: number }[]>([]);
  let selectionsAnswer = ref<
    {
      selection_key: string[];
      selection_id: number;
    }[]
  >([]);
  let judgesAnswer = ref<{ judge_key: string; judge_id: number }[]>([]);
  const getCurrentExamTopic = async () => {
    if (!test_id) {
      router.replace('/');
      return;
    }
    try {
      const { data } = await getStudentAppExamQuestions(Number(test_id));
      topic.value = { ...data, time_limit: data.time_limit.toString() } as ExamTopic;

      for (const _i in topic.value.singles) {
        singlesAnswer.value.push({
          single_key: '',
          single_id: 0,
        });
      }
      for (const _i in topic.value.selections) {
        selectionsAnswer.value.push({
          selection_key: [],
          selection_id: 0,
        });
      }
      for (const _i in topic.value.judges) {
        judgesAnswer.value.push({
          judge_key: '',
          judge_id: 0,
        });
      }
      loading.value = false;
    } catch {
      router.back();
    }
  };
  onMounted(() => {
    getCurrentExamTopic();
  });

  interface Singles {
    single_key: string;
    single_id: number;
  }
  interface Judges {
    judge_key: string;
    judge_id: number;
  }
  interface Selections {
    selection_key: string[] | string;
    selection_id: number;
  }
  interface Answer {
    singles: Singles[];
    selections: Selections[];
    judges: Judges[];
  }
  let answer = reactive<Answer>({
    singles: [],
    selections: [],
    judges: [],
  });

  const handleAnswerChange = (answerArr: Singles[] | Judges[] | Selections[], type: string) => {
    switch (type) {
      case 'singles':
        answer.singles = answerArr as Singles[];
        break;
      case 'judge':
        answer.judges = answerArr as Judges[];
        break;
      case 'selections':
        answer.selections = answerArr as Selections[];
        break;
    }
  };
  // 计算耗时
  let elapsedTime = ref(0);
  const calculateElapsedTime = (time: number) => {
    elapsedTime.value = time;
  };
  // 交卷
  const submitExam = async () => {
    const singles = answer.singles.map((item) => item.single_id === 0);
    const selections = answer.selections.map(
      (item) => item.selection_id === 0 || item.selection_key.length === 0
    );
    const judges = answer.judges.map((item) => item.judge_id === 0);
    if (
      singles.length === 0 ||
      selections.length === 0 ||
      judges.length === 0 ||
      singles.includes(true) ||
      selections.includes(true) ||
      judges.includes(true)
    ) {
      Snackbar['warning']({
        content: '请完成所有题目',
        duration: 1500,
      });
      return;
    }
    const { getUserId } = storeToRefs(useUserInfoStoreWithOut());

    const { status, msg } = (await studentAppSubmitExam(
      getUserId.value,
      Number(test_id),
      elapsedTime.value,
      0,
      answer.singles,
      answer.selections,
      answer.judges
    )) as any;

    if (status === 200) {
      Snackbar['success']({
        content: msg,
        duration: 1500,
      });
      window.location.reload();
    }
  };
  // 时间到了自动交卷
  const examTimeEnd = async () => {
    const { getUserId } = storeToRefs(useUserInfoStoreWithOut());

    const { status } = await studentAppSubmitExam(
      getUserId.value,
      Number(test_id),
      elapsedTime.value,
      0,
      answer.singles,
      answer.selections,
      answer.judges
    );
    if (status === 200) {
      Snackbar['success']({
        content: '时间到，自动交卷',
        duration: 1500,
      });
      window.location.reload();
    }
  };

  const handleRadioChange = (id: number, index: number) => {
    singlesAnswer.value[index].single_id = id;

    handleAnswerChange(singlesAnswer.value, 'singles');
  };

  const handleSelectChange = (id: number, index: number) => {
    selectionsAnswer.value[index].selection_id = id;
    handleAnswerChange(selectionsAnswer.value, 'selections');
  };

  const handleJudgeChange = (id: number, index: number) => {
    judgesAnswer.value[index].judge_id = id;
    handleAnswerChange(judgesAnswer.value, 'judge');
  };

  const isAllDo = computed(() => {
    const allLength =
      topic.value!.singles.length + topic.value!.selections.length + topic.value!.judges.length;
    const selectionsAnswerLength = selectionsAnswer.value.filter(
      (item) => item.selection_id !== 0
    ).length;
    const judgesAnswerLength = judgesAnswer.value.filter((item) => item.judge_id !== 0).length;
    const singlesAnswerLength = singlesAnswer.value.filter((item) => item.single_id !== 0).length;
    const doLength = selectionsAnswerLength + judgesAnswerLength + singlesAnswerLength;

    return allLength === doLength;
  });
</script>
<style scoped>
  :deep(.var-progress__linear-label) {
    @apply transform -rotate-90;
  }

  .active {
    @apply w-[10vw] rounded-full bg-[#12B7ED] flex items-center justify-center bg-opacity-30 text-[#585757];
  }
</style>
